<template>
  <div class="transit-scan">
    <div class="scan-header">
      <h2>扫码乘车</h2>
      <div class="credit-info" v-if="creditInfo">
        <el-tag :type="creditInfo.canUse ? 'success' : 'danger'">
          信用分：{{ creditInfo.score }}
          <span v-if="!creditInfo.canUse">
            (需要{{ creditInfo.requiredScore }}分)
          </span>
        </el-tag>
      </div>
    </div>

    <div class="scan-content">
      <div class="transit-type">
        <el-radio-group v-model="transitType" @change="handleTransitTypeChange">
          <el-radio-button label="BUS">公交</el-radio-button>
          <el-radio-button label="SUBWAY">地铁</el-radio-button>
        </el-radio-group>
      </div>

      <div class="line-select">
        <el-select v-model="selectedLine" placeholder="选择线路" @change="handleLineChange">
          <el-option
            v-for="line in transitLines"
            :key="line"
            :label="line"
            :value="line"
          />
        </el-select>
      </div>

      <div class="station-select">
        <el-select v-model="selectedStation" placeholder="选择站点">
          <el-option
            v-for="station in stations"
            :key="station"
            :label="station"
            :value="station"
          />
        </el-select>
      </div>

      <div class="vehicle-info" v-if="selectedLine">
        <div class="info-item">
          <span class="label">车辆位置：</span>
          <span>{{ vehicleLocation }}</span>
        </div>
        <div class="info-item">
          <span class="label">预计到达：</span>
          <span>{{ estimatedArrivalTime }}分钟</span>
        </div>
      </div>

      <div class="scan-area">
        <div class="qr-code">
          <img src="/images/transit-qr.png" alt="乘车码" />
        </div>
        <p class="scan-tip">请将乘车码对准闸机扫描区域</p>
      </div>

      <div class="action-buttons">
        <el-button
          type="primary"
          size="large"
          :disabled="!canStartTransit"
          @click="startTransit"
        >
          开始乘车
        </el-button>
      </div>
    </div>

    <!-- 乘车记录对话框 -->
    <el-dialog
      v-model="recordDialogVisible"
      title="乘车记录"
      width="400px"
    >
      <div class="record-info">
        <div class="info-item">
          <span class="label">线路：</span>
          <span>{{ currentRecord?.lineNumber }}</span>
        </div>
        <div class="info-item">
          <span class="label">起始站：</span>
          <span>{{ currentRecord?.startStation }}</span>
        </div>
        <div class="info-item">
          <span class="label">开始时间：</span>
          <span>{{ formatDateTime(currentRecord?.startTime) }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="recordDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="endTransit">结束乘车</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getTransitLines, getStations, getVehicleLocation, getEstimatedArrivalTime, startTransit, endTransit } from '@/api/transit'
import { checkCreditTransit } from '@/api/credit'
import { formatDateTime } from '@/utils/format'

export default {
  name: 'TransitScan',
  setup() {
    const router = useRouter()
    const transitType = ref('BUS')
    const selectedLine = ref('')
    const selectedStation = ref('')
    const transitLines = ref([])
    const stations = ref([])
    const vehicleLocation = ref('')
    const estimatedArrivalTime = ref(0)
    const creditInfo = ref(null)
    const recordDialogVisible = ref(false)
    const currentRecord = ref(null)

    // 是否可以开始乘车
    const canStartTransit = computed(() => {
      return creditInfo.value?.canUse && selectedLine.value && selectedStation.value
    })

    // 获取信用信息
    const loadCreditInfo = async () => {
      try {
        const response = await checkCreditTransit()
        creditInfo.value = response
      } catch (error) {
        ElMessage.error('获取信用信息失败')
      }
    }

    // 处理交通类型变化
    const handleTransitTypeChange = async () => {
      selectedLine.value = ''
      selectedStation.value = ''
      await loadTransitLines()
    }

    // 处理线路变化
    const handleLineChange = async () => {
      selectedStation.value = ''
      await loadStations()
      await loadVehicleInfo()
    }

    // 加载线路信息
    const loadTransitLines = async () => {
      try {
        transitLines.value = await getTransitLines(transitType.value)
      } catch (error) {
        ElMessage.error('获取线路信息失败')
      }
    }

    // 加载站点信息
    const loadStations = async () => {
      if (!selectedLine.value) return
      try {
        stations.value = await getStations(transitType.value, selectedLine.value)
      } catch (error) {
        ElMessage.error('获取站点信息失败')
      }
    }

    // 加载车辆信息
    const loadVehicleInfo = async () => {
      if (!selectedLine.value || !selectedStation.value) return
      try {
        vehicleLocation.value = await getVehicleLocation(transitType.value, selectedLine.value)
        estimatedArrivalTime.value = await getEstimatedArrivalTime(
          transitType.value,
          selectedLine.value,
          selectedStation.value
        )
      } catch (error) {
        ElMessage.error('获取车辆信息失败')
      }
    }

    // 开始乘车
    const startTransit = async () => {
      try {
        currentRecord.value = await startTransit({
          transitType: transitType.value,
          lineNumber: selectedLine.value,
          startStation: selectedStation.value
        })
        recordDialogVisible.value = true
      } catch (error) {
        ElMessage.error(error.message || '开始乘车失败')
      }
    }

    // 结束乘车
    const endTransit = async () => {
      try {
        await endTransit(currentRecord.value.id)
        ElMessage.success('乘车结束')
        recordDialogVisible.value = false
        router.push('/transit/records')
      } catch (error) {
        ElMessage.error(error.message || '结束乘车失败')
      }
    }

    onMounted(() => {
      loadCreditInfo()
      loadTransitLines()
    })

    return {
      transitType,
      selectedLine,
      selectedStation,
      transitLines,
      stations,
      vehicleLocation,
      estimatedArrivalTime,
      creditInfo,
      recordDialogVisible,
      currentRecord,
      canStartTransit,
      handleTransitTypeChange,
      handleLineChange,
      startTransit,
      endTransit,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.transit-scan {
  padding: 20px;
}

.scan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.scan-content {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.transit-type {
  margin-bottom: 20px;
  text-align: center;
}

.line-select,
.station-select {
  margin-bottom: 20px;
}

.vehicle-info {
  margin: 20px 0;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.info-item {
  display: flex;
  margin: 5px 0;
}

.info-item .label {
  width: 100px;
  color: #909399;
}

.scan-area {
  margin: 30px 0;
  text-align: center;
}

.qr-code {
  width: 200px;
  height: 200px;
  margin: 0 auto;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.qr-code img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.scan-tip {
  margin-top: 10px;
  color: #909399;
}

.action-buttons {
  text-align: center;
  margin-top: 20px;
}

.record-info {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}
</style> 